var lastUpdate;
var container;
var camera, scene, renderer;
var uniforms;

async function init() {
	container = document.getElementById('container');
	camera = new THREE.Camera();
	camera.position.z = 1;
	scene = new THREE.Scene();

	// 从zip文件中获取视频相关逻辑
	const zipUrl = container.dataset.zipUrl; // 替换为实际的zip文件链接
	const response = await fetch(zipUrl);
	const blobData = await response.blob();
	const zip = await JSZip.loadAsync(blobData);
	const configFileEntry = zip.file('output.mp4');
	if (!configFileEntry) {
		console.error('ZIP文件中缺少config.json文件，无法获取视频配置信息');
		onVideoEnded();
		return;
	}

	// 读取config.json文件内容
	const configFile = await zip.file('config.json').async('string');
	const config = JSON.parse(configFile);
	const videoFileName = config.portrait.path; // 获取配置中指定的mp4文件名

	// 获取zip中的视频文件数据并转为URL
	const videoBlob = await zip.file(videoFileName).async('blob');
	const videoUrl = URL.createObjectURL(videoBlob);

	var video = document.createElement('video');
	video.src = videoUrl;
	video.muted = true;
	video.addEventListener('ended', onVideoEnded);
	video.play();
	videoTexture = new THREE.VideoTexture(video);
	videoTexture.minFilter = THREE.LinearFilter;
	videoTexture.magFilter = THREE.LinearFilter;
	videoTexture.format = THREE.RGBAFormat;


	// shader stuff
	uniforms = {
		time: { type: "f", value: 1.0 },
		texture: { type: "sampler2D", value: videoTexture }
	};
	var material = new THREE.ShaderMaterial({
		uniforms: uniforms,
		vertexShader: `varying vec2 vUv;
	  void main() {
		vUv = uv;
		gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
	  }`,
		fragmentShader: `#ifdef GL_ES
	  precision highp float;
	  #endif

	  uniform float time;
	  uniform sampler2D texture;
	  varying vec2 vUv;

	  void main( void ) {
		gl_FragColor = vec4(
		texture2D(texture, vec2(0.5+vUv.x/2., vUv.y)).rgb,
		texture2D(texture, vec2(vUv.x/2., vUv.y)).r
		);
	  }`,
		transparent: true
	});
	lastUpdate = new Date().getTime();
	var geometry = new THREE.PlaneBufferGeometry(2, 2);
	// 给网格对象设置一个名称，方便后续查找移除
	var mesh = new THREE.Mesh(geometry, material);
	mesh.name = 'videoMesh';
	mesh.scale.setScalar(1);
	scene.add(mesh);
	renderer = new THREE.WebGLRenderer({ alpha: true });
	renderer.setPixelRatio(window.devicePixelRatio / 1);

	container.appendChild(renderer.domElement);

	document.getElementById('play-button').addEventListener('click', e => { video.play(); });
	renderer.setSize(330, 586);
	animate();
}

function animate() {
	var currentTime = new Date().getTime()
	var timeSinceLastUpdate = currentTime - lastUpdate;
	lastUpdate = currentTime;
	requestAnimationFrame(animate);
	render(timeSinceLastUpdate);

}

function render(timeDelta) {
	uniforms.time.value += (timeDelta? timeDelta / 1000 : 0.05);
	renderer.render(scene, camera);
}


function onVideoEnded() {
	console.log('视频播放完毕');
	var channel = new QWebChannel(qt.webChannelTransport, function (channel) {
		var mainWindowObj = channel.objects.mainWindow;
		console.log('视频ended事件触发');
		setTimeout(function () {
			mainWindowObj.pyqt_slot_video_ended();
		}, 200);  // 延迟1000毫秒（1秒）
	});

	// 释放视频的对象URL
	const videoElement = document.querySelector('video');
	if (videoElement.src) {
		URL.revokeObjectURL(videoElement.src);
	}

	// 移除场景中的网格对象
	const mesh = scene.getObjectByName('videoMesh');
	if (mesh) {
		scene.remove(mesh);
	}

	// 释放纹理资源
	uniforms.texture.value.dispose();
	uniforms.texture.value = null;

	// 清理渲染器并移除DOM元素
	renderer.dispose();
	container.removeChild(renderer.domElement);
}


init();